package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shops/models"
)

type ShopController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Date interface{} `json:"date"`
}

// 添加
func (c *ShopController) Add() {
	name := c.GetString("name")
	address := c.GetString("address")
	tel := c.GetString("tel")
	cate := c.GetString("cate")
	shops := models.Shop{
		Name:    name,
		Address: address,
		Tel:     tel,
		Cate:    cate,
	}
	err := models.DB.Create(&shops).Error
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Date: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Date: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

// 列表展示
func (c *ShopController) List() {
	var shop []models.Shop
	err := models.DB.Find(&shop).Error
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "展示失败",
			Date: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Date: shop,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

// 删除
func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		data := JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Date: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	} else {
		data := JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Date: nil,
		}
		c.Data["json"] = data
		c.ServeJSON()
	}
}
